function creat(cr) {
    return document.createElement(cr);
}
function getid (id) {
    return document.getElementById(id);
}
function getcn (cn) {
    return document.getElementsByClassName(cn);
}
var mspan = getid("mspan");
var v = getid("v");
var longest = getid("longest");
// longest.innerText = "最高得分："+parseInt(getCookie('long'));
if (parseInt(getCookie('long')) != NaN) {
    longest.innerText = "最高得分："+parseInt(getCookie('long'));
}


var continer = getid ("continer");
for (var i = 0;i< 20;i++) {   
    var xh = creat("div"); 
    xh.className = "xheng";      
    for (var j = 0;j< 30;j++) {       
        var check = creat("div");
        check.setAttribute('X', i);
        check.setAttribute('Y', j);
        check.setAttribute('state', 1);
        check.className = "check";
        xh.appendChild(check);
    }
    continer.appendChild(xh);
}

var arr = [];
arr[0] = 32;
arr[1] = 31;

var count = 2;
var long = 0;
var velocity = 300;

var lr = 1;

var check = getcn("check");

//蛇蛇生成函数
function aa () {
    for (var i = 0;i<arr.length;i++) { 
        if (arr[i] >= 0&& arr[i] < 600)   
        check[arr[i]].style.background = "red";        
    }
}
aa();  //蛇蛇初始化

//蛇蛇去除
function bb () {
    for (var i = 0;i<arr.length;i++) {
        if (arr[i] >= 0&& arr[i] < 600) 
        check[arr[i]].style.background = "linear-gradient(135deg,greenyellow,yellowgreen)";
    }
}

//移动封装,移动的数组就是移动的灵魂
function cc(ev){
    for(var i=arr.length-1;i>=1;i--){
        arr[i]=arr[i-1];
    }   
    arr[0] = arr[0]+(ev);
    if ((ev == 1) && (parseInt(arr[0]/30) - parseInt(arr[1]/30))) {
        arr[0] = arr[0] - 30;
        lr = 1;
    }
    if (((ev == -1) && (parseInt(arr[1]/30) - parseInt(arr[0]/30)))||(arr[0] == -1)) {
        arr[0] = arr[0] + 30;
        lr = -1;
    }
}

//移动函数中的过程的封装
function gg (gc) {
    bb();
    cc(gc);
    ee();
    pp();
    aa();  
}

// 移动函数
function ff() {
    var cha = arr[0] - arr[1];
    if(velocity > 150) {
        velocity = 310 - count*10;
    }else {
         velocity = 150;
    }
    switch(cha){
        case -1: 
            gg(cha);
            break;
        case 1:
            gg(cha);
            break;
        case 30:
            gg(cha);
            break;
        case -30:
            gg(cha);
            break;
        default:
            gg(lr);
            break;
    }
}
var timer = setInterval(ff,velocity) 

//食物生成函数
var random;
function dd(){
    while(true){
        var s=1;
      random=parseInt(Math.random()*600) ;
      for(var i=0;i<arr.length;i++){
        if(arr[i]==random){ 
            s=0;
            break;   
        }
      }
      if(s!=0){
          break;
      }
    }
    check[random].style.background="red";
}
dd();

// 蛇蛇长身体了
function ee () {
    if (arr[0] == random) { 
        arr[arr.length] = arr[arr.length-1]*2 - arr[arr.length-2];
        count++;
        mspan.innerText = "本局得分："+ (count-2);
        v.innerHTML = `当前速度 (${velocity}ms)<sup>-1</sup>`
        
        dd();       
    }
}



//吃屁屁啦！,上墙啦
var si = getid("si");
var sisp = getid("sisp");
function pp(){
    var ppp = 1;
    for(var i=1;i<arr.length-1;i++){
        if(arr[0]==arr[i]){   
            clearInterval(timer);     
            si.style.display = "block";
            sisp.innerText = "你个吃货，自己的尾巴都吃！！！";
            if (count-2 >parseInt(getCookie('long'))) {
                long = count-2;
                setCookie("long", long);
                longest.innerText = "最高记录:"+parseInt(getCookie('long'));
            }
            ppp = 0;
            setTimeout(
                function () {
                    arr = [];
                },100
            )
            break;
        }
    }   
    if (arr[0] != -1 && ppp == 1) {
        if (!check[arr[0]]) {
            clearInterval(timer);
            si.style.display = "block";
            sisp.innerText = "黄天在上，厚土在下！！！";
            if (count-2 >parseInt(getCookie('long'))) {
                long = count-2;
                setCookie("long", long);
                longest.innerText = "最高记录:"+parseInt(getCookie('long'));
            }
            setTimeout(
                function () {
                    arr = [];
                }, 100
            )
        }
    } 
    
}



// 键盘事件
document.onkeydown = function (event) {
    var e = event || window.event || arguments.callee.caller.arguments[0];

    if (e && e.keyCode == 38) {
        // console.log('38=上键');
        if ((arr[0] - arr[1]) != 30) {
            clearInterval(timer);
            gg(-30);
            timer = setInterval(ff, velocity)
        }

    }

    if (e && e.keyCode == 37) {
        // console.log('37=左键');
        if ((arr[0] - arr[1]) != 1 && (arr[0] - arr[1]) != -29) {
            clearInterval(timer);
            gg(-1);
            timer = setInterval(ff, velocity)
        }

    }

    if (e && e.keyCode == 40) {
        // console.log('40=下键');
        if ((arr[0] - arr[1]) != -30) {
            clearInterval(timer);
            gg(30);
            timer = setInterval(ff, velocity)
        }

    }

    if (e && e.keyCode == 39) {
        // console.log('39=右键');
        if ((arr[0] - arr[1]) != -1 && (arr[0] - arr[1]) != 29) {
            clearInterval(timer);
            gg(1);
            // timer = setInterval(ff, velocity)
            timer = setInterval(
                function () {
                  ff();
                }
                , velocity)
        }

    }

};

//写cookies
function setCookie(name, value) {
    var Days = 1;
    var exp = new Date();
    exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
    document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
}
//读cookies
function getCookie(name) {
    var arr;
    var reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg)) {
        return unescape(arr[2]);
    } else
        return null;
}
//删除cookise
function delCookie(name) {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = getCookie(name);
    if (cval != null)
        document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
} 